<template>
  <el-dialog
      v-model="dialogVisible"
      title="新增红冲"
      width="20%"
      :before-close="handleClose"
  >
    <div class="content">
      <el-form
        ref="rulesFormRef"
        :model="rulesForm"
        :rules="rules"
      >
        <el-form-item label="红冲金额" prop="hongChongAmount">
          <el-input v-model="rulesForm.hongChongAmount" placeholder="请输入红冲金额"></el-input>
        </el-form-item>
        <el-form-item label="红冲原因" prop="hongChongReason">
          <el-input
              v-model="rulesForm.hongChongReason"
              :rows="2"
              type="textarea"
              placeholder="请输入红冲原因"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false" class="button_cancel2">取消</el-button>
        <el-button type="primary" @click="onConfirm" class="button_view">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref,watch,reactive} from "vue";
import {ElDialog,ElMessage,ElForm,ElFormItem,ElInput} from "element-plus";
import {invoiceApi} from "@/api/lease";

const props = defineProps({
  visible:{
    type:Boolean,
    default:false
  },
  form:{
    type:Object,
    default: {}
  }
});

console.log('form',props.form)
const rulesForm = reactive({
  hongChongAmount:'',
  hongChongReason:'',
  businessId:''
});

const rules = reactive({
  hongChongAmount: [
    { required: true, message: '红冲金额不能为空!', trigger: 'blur' },
  ],
  hongChongReason: [
    { required: true, message: '红冲原因不能为空!', trigger: 'blur' },
  ]
});
let emits = defineEmits(['update:visible','onConfirm'])
const dialogVisible = ref(props.visible);

const handleClose = () => {
  // 需要修改父组件的数据
  emits('update:visible',false);
}

const rulesFormRef = ref(null);
const onConfirm = () => {
  rulesForm.businessId = props.form.invoiceId;
  rulesFormRef.value.validate((valid, fields)=>{
    if (valid) {
      invoiceApi.addHongChong(rulesForm).then(res=>{
        if(res.code == 200){
          ElMessage.success('红冲成功!');
          handleClose();
          emits('onConfirm');
        }
      });
    }
  });

}

// 监听visible的变化 只能监听第一次的变化
watch(()=> props.visible, value => {
  dialogVisible.value = value;
})

// 监听组件内部的dialogVisible变化
watch(() => dialogVisible.value, value => {
  emits('update:visible', value)
})
</script>
